package org.reborn.math.util

import scala.math
import org.reborn.math._

object MathUtils {

  def dist(p1:VectorI,p2:VectorI):Float = {
    require(p1.vec.size == p2.vec.size)
    MathUtils.sqrt((p2 - p1).vec.reduceLeft(_*_).asInstanceOf[Float])
  }
  
  def OriginF(dimension:Int) = VectorF(List.fill(dimension)(0.0f))
  
  def sqrt(flt:Float):Float = {
    math.sqrt(flt.asInstanceOf[Double]).asInstanceOf[Float]
  }
  
  def dist(p1:VectorF,p2:VectorF):Float = {
    require(p1.length == p2.length)
    MathUtils.sqrt((p2 - p1).magnitude)
  }
  
  def dist(point:VectorF,plane:Plane3F):Float = {
    require(point.length == 3)
    val diff = point - plane.point
    val dist = diff dot plane.normal
    dist
  }
  
  def intersectionDist(p1:VectorF,p2:VectorF,plane:Plane3F):Float = {
    require(p1.length == 3 && p2.length == 3)
    val d = plane.point dot plane.normal
    val lineVec = p2 - p1
    val num = d - (p1 dot plane.normal)
    val denom = lineVec dot plane.normal 
    num / denom
  }
  
  def normalize(p:VectorF) = {
    val len = dist(OriginF(p.length),p)
    assert(len!=0.0f)
    p / len
  }
  
  def wrappedIndex(index:Int,maxIndex:Int):Int = {
    val value = index % maxIndex
    if(value < 0 )
      maxIndex + value
    else
      value  
  }
  
  /**
   * Get a random number as a Float with a range between
   * -1.0 and 1.0
   */
  def random() = {
    (math.random.asInstanceOf[Float] * 2.0f) - 1.0f
  }
}
